package com.kelvin.backend.common.log;

import com.kelvin.backend.common.util.AnnotationUtil;
import com.kelvin.backend.common.util.json.JacksonUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * <p>Title: WebLogAop</p>
 * <p>Description: </p>
 *
 * @author Kelvin.Chen
 * @blame Lenovo
 * @datetime 2020/2/24 18:47
 */
@Aspect
@Component
public class WebLogAop {

    private static final Logger log = LoggerFactory.getLogger(WebLogAop.class);

    /**
     * 换行符
     */
    private static final String LINE_SEPARATOR = System.lineSeparator();

    private WebLog webLog;

    /**
     * 以自定义@WebLog注解作为切入点
     */
    @Pointcut("@annotation(com.kelvin.backend.common.log.WebLog)")
    public void webLog() {
    }


    /**
     * 切点切入前，打印相关信息
     *
     * @param jp
     * @throws ClassNotFoundException
     */
    @Before("webLog()")
    public void doBefore(JoinPoint jp) throws Throwable {
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 获取 @WebLog 注解
        webLog = (WebLog) AnnotationUtil.getAnnotation(jp, WebLog.class);

        // 打印请求相关参数
        log.info("========================================== Start ==========================================");
        // 打印请求 url
        log.info("接口请求路径     -> {}", request.getRequestURL().toString());
        // 打印描述信息
        log.info("接口描述         -> {}", webLog.description());
        // 打印 HTTP Method，接口请求方式
        log.info("接口请求方式     -> {}", request.getMethod());
        // 打印调用 controller的全路径已经执行方法
        log.info("接口类名        -> {}.{}", jp.getSignature().getDeclaringTypeName(), jp.getSignature().getName());
        // 打印请求的IP
        log.info("接口请求IP      -> {}", request.getRemoteAddr());
        // 打印请求入参
        if (webLog.showParam()) {
            log.info("接口请求参数     -> {}", Arrays.asList(jp.getArgs()));
        }
    }

    /**
     * 处理，打印处理结果
     *
     * @param pjp
     * @return
     * @throws Throwable
     */
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = pjp.proceed();
        // 打印出参
        if (webLog.showResult()) {
            log.info("接口响应结果     -> {}", JacksonUtil.toJsonStr(result));
        }
        // 执行耗时
        log.info("接口耗时        -> {} 毫秒", System.currentTimeMillis() - startTime);

        return result;
    }

    /**
     * 切点结束后
     */
    @After("webLog()")
    public void doAfter() {
        // 接口结束后换行，方便分割查看
        log.info("=========================================== End ===========================================" + LINE_SEPARATOR);
    }
}
